import { Column, Entity, JoinTable, OneToMany, PrimaryColumn, TableInheritance } from 'typeorm'
import { ResourceComment } from './comment.model'
import { ResourceUp } from './up.model'
import { RatingAmongCount } from '@boticord/common'
import { boostLevelAmount, NotifySettings, ResourceBoost } from '@boticord/resources-client'

export enum ResourceStatus {
  Hidden,
  Public,
  Banned,
  Pending,
}

export class PremiumResource {
  @Column({ type: 'boolean', default: false })
  declare active: boolean

  @Column({ nullable: true, default: null })
  declare splashURL?: string

  @Column({ type: 'boolean', default: false })
  declare autoFetch: boolean

  @Column({ nullable: true, default: null })
  declare bannerURL?: string
}

// make sure you're making changes in both files with Resource and PendingBot (bot.model.ts) models
@Entity()
@TableInheritance({ column: { type: 'varchar', name: 'type' } })
export class Resource {
  @PrimaryColumn({ unique: true })
  declare id: string

  @OneToMany(() => ResourceBoost, boost => boost.resource)
  declare boosts: ResourceBoost[]

  @Column()
  declare name: string

  @Column()
  declare shortDescription: string

  @Column()
  declare description: string

  @Column({ nullable: true, default: null })
  declare avatar?: string

  @Column({ nullable: true, default: null })
  declare shortLink?: string

  @Column()
  declare inviteLink: string

  @Column({ default: 0 })
  declare standardBannerID: number

  @Column()
  declare owner: string

  @Column({
    type: 'enum',
    enum: ResourceStatus,
    default: ResourceStatus.Pending,
  })
  declare status: ResourceStatus

  @OneToMany(() => ResourceComment, c => c.resource)
  @JoinTable()
  declare comments: ResourceComment[]

  @OneToMany(() => ResourceUp, up => up.resource)
  @JoinTable()
  declare ups: ResourceUp[]

  @Column({ type: 'jsonb' })
  declare ratings: RatingAmongCount[]

  @Column(() => PremiumResource)
  declare premium: PremiumResource

  @Column('int', { array: true, default: [] })
  declare tags: number[]

  @Column(() => NotifySettings)
  declare notify: NotifySettings

  get boostLevel() {
    return Object.entries(boostLevelAmount)
      .reverse()
      .find(([ _, amount ]) => amount >= this.boosts.length)!
  }
}
